<template>
	<view class="school_content">

		<view style="display:none;">
			<button wx:if="{{canIUse}}" open-type="getUserInfo" bindgetuserinfo="bindGetUserInfo">授权登录</button>
			<view wx:else>请升级微信版本</view>
		</view>

	</view>
</template>

<script>
	export default {
		data() {
			return {
				canIUse: uni.canIUse('button.open-type.getUserInfo'),
				redirect_page: '',
			}
		},
		onLoad(options) {

			let redirect_page = "";
			if (options.scene) {
				const scene = decodeURIComponent(options.scene);


				if (sceneArr[0] == 'task2' && sceneArr[1]) {
					redirect_page = '/pages/task2/task2?id=' + sceneArr[1];
				} else if (sceneArr[0] == 'task' && sceneArr[1]) {
					redirect_page = '/pages/booking/taskequipmentlist/taskequipmentlist?id=' + sceneArr[1];
				} else if (sceneArr[0] == 'toequipbooking' && sceneArr[1]) {
					redirect_page = '/pages/booking/toequipbooking/toequipbooking?id=' + sceneArr[1];
				}

				this.setData({
					redirect_page: redirect_page
				})
			} else if (options.redirect_page) {
				const options_redirect_page = options.redirect_page;

				let paramStr = "";
				for (var i in options) {
					if (i != 'redirect_page') {
						paramStr += i + '=' + options[i] + '&';
					}
				}

				if (paramStr.length > 0) paramStr = paramStr.substr(0, paramStr.length - 1);


				if (options_redirect_page == 'taskequipmentlist' || options_redirect_page == 'toequipbooking' ||
					options_redirect_page == 'tobooking') {
					redirect_page = '/pages/booking/' + options_redirect_page + '/' + options_redirect_page + '?' +
						paramStr;
				} else if (paramStr) {
					redirect_page = '/pages/' + options_redirect_page + '/' + options_redirect_page + '?' + paramStr;
				} else {
					redirect_page = '/pages/' + options_redirect_page + '/' + options_redirect_page;
				}

				this.redirect_page = redirect_page

			}

			this.mylogin();

		},
		methods: {
			mylogin: function(e) {
				var that = this;
				if (uni.getStorageSync("token") && uni.getStorageSync("token") != "") {
					that.jumppage(that);
					return;
				};

				uni.showLoading({
					title: '加载中...',
				})

				uni.login({
					success(res) {
						if (res.code) {

							let params = 'code=' + res.code
							this.$request.request("api/index/login", params, 0, 'get', false).then(res2 => {

								let res2w = res2.data;
								if (typeof res2w == 'string') {
									let str22 = res2w.replace(/\ufeff/g, ""); //去除反斜杠
									res2w = JSON.parse(str22); //string转object
								}

								if (res2w.status == 1) {

									const res2_data_data = res2w.data;
									const isuser = res2_data_data.isuser;
									const session_key = res2_data_data.session_key;
									if (isuser == 1) {
										const userinfo = {
											avatarUrl: res2_data_data.avatarUrl,
											city: res2_data_data.city,
											country: res2_data_data.country,
											gender: res2_data_data.gender,
											language: res2_data_data.language,
											nickName: res2_data_data.nickName,
											province: res2_data_data.province,
										};
										//app.globalData.userInfo = userinfo;
										uni.setStorageSync('userInfo', userinfo);
									}
									uni.setStorageSync('token', res2_data_data.token);
									uni.setStorageSync('isuser', isuser);
									uni.setStorageSync('session_key', session_key);

									that.jumppage(that);

								} else if (res2w.status == -2) {

									uni.showModal({
										title: "提示",
										content: res2w.msg,
										success: function(t) {

											t.confirm ? that.mylogin() : t.cancel &&
												that.mylogin()
										}
									})
								} else {

									uni.showModal({
										title: "提示",
										content: "api接口出错",
										success: function(t) {
											t.confirm ? that.mylogin() : t.cancel &&
												that.mylogin()
										}
									})

								}
								uni.hideLoading();

							})

						} else {
							console.log('登录失败！' + res.errMsg)
						}

					},
					fail(err) {
						console.log('登录失败！' + err.errMsg)
						uni.hideLoading();
					}
				})
			},
			login() {

				uni.login({
					"provider": "weixin",
					"onlyAuthorize": true, // 微信登录仅请求授权认证
					success: function(event) {
						const {
							code
						} = event
						//客户端成功获取授权临时票据（code）,向业务服务器发起登录请求。
						uni.request({
							url: 'https://www.example.com/loginByWeixin', //仅为示例，并非真实接口地址。
							data: {
								code: event.code
							},
							success: (res) => {
								//获得token完成登录
								uni.setStorageSync('token', res.token)
							}
						});
					},
					fail: function(err) {
						// 登录授权失败
						// err.code是错误码
					}
				})

			},

			bindGetUserInfo: function(e) {

				const that = this;
				const redirect_page = this.redirect_page;


				uni.checkSession({
					success(e) {

						//session_key 未过期，并且在本生命周期一直有效
					},
					fail() {
						uni.removeStorageSync('token');
						uni.removeStorageSync('isuser');
						uni.redirectTo({
							url: '/pages/login/login',
						})
						return;
					}
				})


				uni.getUserProfile({
					desc: '用于完善会员资料',
					success: function(res) {
						var userInfo = res.userInfo
						var nickName = userInfo.nickName
						var avatarUrl = userInfo.avatarUrl
						var gender = userInfo.gender //性别 0：未知、1：男、2：女
						var province = userInfo.province
						var city = userInfo.city
						var country = userInfo.country
						var encryptedData = res.encryptedData
						var iv = res.iv
						var rawData = res.rawData
						var signature = res.signature


						let params = {
								nickName: nickName,
								avatarUrl: avatarUrl,
								gender: gender,
								province: province,
								city: city,
								country: country,
								encryptedData: encryptedData,
								iv: iv,
								rawData: rawData,
								signature: signature,
							},

							this.$request.request("api/index/touserinfo?token=" + uni.getStorageSync(
								'token'), params, 0, 'get', false).then(res2 => {
								if (res2.data.status == 1) {

									if (redirect_page != "") {
										uni.redirectTo({
											url: redirect_page,
										})
									} else {
										uni.redirectTo({
											url: '/pages/index/index',
										})
									}
								} else {
									uni.showModal({
										title: "提示",
										content: res2.data.msg,
										success: function(t) {

											if (t.confirm) {
												that.bindGetUserInfo(e);
											} else if (t.cancel) {
												that.jumppage(that);
											}

										}
									})
								}

							})
					}
				})
			},

			jumppage: function(options) {
				const redirect_page = options.data.redirect_page;

				if (redirect_page != "") {
					uni.redirectTo({
						url: redirect_page,
					})
				} else {
					uni.redirectTo({
						url: '/pages/index/index',
					})
				}
				return;
			},
		}
	}
</script>

<style>
	page {}

	.school_content {
		display: flex;
		flex-direction: column;
		font-weight: bold;
	}

	.card1 {
		display: flex;
		flex-direction: row;
		justify-content: space-around;
		justify-items: center;
		align-items: center;
		margin-top: 10px;

	}

	.welcome_img {
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		width: 100%;
	}

	.welcome_img image {
		border: 1px solid #cccccc;
		height: 240px;
		width: 100%;
	}

	.card_sub {
		display: flex;
		flex-direction: row;
		background-color: white;
		width: 100%;
		margin: 5px 5px;
		padding: 5px 0px;

		justify-items: center;
		align-items: center;
		justify-content: space-evenly;
	}

	.card_sub text {}

	.icon {
		width: 50px;
		height: 50px;
	}

	.card_sub_big {
		justify-content: center;
	}
</style>